package com.glela.controller;

import com.alibaba.fastjson.JSONObject;
import com.glela.cache.model.RedisKey;
import com.glela.common.util.DateUtil;
import com.glela.live.mapper.LiveOrderMapper;
import com.glela.live.messages.User;
import com.glela.live.model.LiveOrder;
import com.glela.live.model.LiveOrderData;
import com.glela.live.model.LivePlan;
import com.glela.live.model.LiveUserRecordData;
import com.glela.live.service.LiveOrderService;
import com.glela.live.service.LivePlanService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.util.ParameterUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Date;
import java.util.List;

/**
 * Created by jinweiwei on 2018/3/28.
 */
@RequestMapping("/chartsData")
@RestController
public class ChartsDataController extends LiveBaseController{

    @Autowired
    private LivePlanService livePlanService;

    @Autowired
    private LiveOrderService liveOrderService;

    @RequestMapping(value = "/getUserInfoChartData",method = RequestMethod.POST,consumes = "application/json")
    public ResponseEntity<?> getChartData(@RequestBody JSONObject jsonObject){
        int id  = jsonObject.getIntValue("id");
        int interval = jsonObject.getInteger("interval");
        if (ParameterUtils.validParams(id)){
            return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
        }
        LivePlan livePlan = livePlanService.getById(id);
        if (livePlan==null){
            return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C90001), HttpStatus.OK);
        }
        if (livePlan.getStatus()!=2&&livePlan.getStatus()!=3){
            return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C90010), HttpStatus.OK);
        }else {
            if (DateUtil.getMinuteDiff(livePlan.getCreatedDate(),new Date())<interval){
                return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C90010), HttpStatus.OK);
            }
        }
        //查询用户进入离开直播间的总记录数量
        long userRecordSize = redisUtil.llength(RedisKey.REDIS_KEY_LIVE_PLAN_USER_RECORD+id);
        int size = Integer.valueOf(String.valueOf(userRecordSize));
        //分页取数据算页数
        int pagesize = size/1000;
        pagesize = pagesize+(size%10000==0?0:1);
        int[] inData;
        int[] outData;
        //根据步长算周期内需要计算的时间片段个数
        long diffMinutes = 0l;
        if (livePlan.getStatus()!=3){
            diffMinutes = DateUtil.getMinuteDiff(livePlan.getStartTime(),new Date());
        }else{
            diffMinutes = DateUtil.getMinuteDiff(livePlan.getStartTime(),livePlan.getEndTime());
        }
        int intervalPages = Integer.valueOf(String.valueOf(diffMinutes))/interval;
        intervalPages += Integer.valueOf(String.valueOf(diffMinutes))%interval==0?0:1;
        inData = new int[intervalPages];
        outData = new int[intervalPages];
        if (pagesize>0){
            for (int i = 0; i < pagesize; i++) {
                List<String> list = redisUtil.lrange(RedisKey.REDIS_KEY_LIVE_PLAN_USER_RECORD+id,i*1000,(i+1)*1000-1);
                for (String data: list) {
                    JSONObject record = JSONObject.parseObject(data);
                    int subMinute = Integer.valueOf(String.valueOf(DateUtil.getMinuteDiff(livePlan.getStartTime(),record.getDate("createdDate"))));
                    if (subMinute>=0){
                        int currentSize = 0;
                        if (subMinute/interval==0){
                            currentSize = subMinute/interval;
                        }else{
                            currentSize = subMinute/interval+1;
                        }
                        if (currentSize<=(intervalPages-1)){
                            if (record.getIntValue("action")==1){
                                outData[currentSize] = outData[currentSize]+1;
                            }else {
                                inData[currentSize] = inData[currentSize]+1;
                            }
                        }
                    }
                }
            }
        }
        LiveUserRecordData liveUserRecordData = new LiveUserRecordData();
        liveUserRecordData.setInterval(interval);
        liveUserRecordData.setStartDate(livePlan.getStartTime());
        liveUserRecordData.setInData(inData);
        liveUserRecordData.setOutData(outData);
        return new ResponseEntity<>(new ResponseResultModel<>(liveUserRecordData), HttpStatus.OK);
    }

    @RequestMapping(value = "/getOrderInfoChartData",method = RequestMethod.POST,consumes = "application/json")
    public ResponseEntity<?> getOrderInfoChartData(@RequestBody JSONObject jsonObject){
        int id  = jsonObject.getIntValue("id");
        int interval = jsonObject.getInteger("interval");
        if (ParameterUtils.validParams(id)){
            return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
        }
        LivePlan livePlan = livePlanService.getById(id);
        if (livePlan==null){
            return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C90001), HttpStatus.OK);
        }
        if (livePlan.getStatus()!=2&&livePlan.getStatus()!=3){
            return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C90010), HttpStatus.OK);
        }else {
            if (DateUtil.getMinuteDiff(livePlan.getCreatedDate(),new Date())<interval){
                return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C90010), HttpStatus.OK);
            }
        }
        //查询所有下单记录
        int size = liveOrderService.getSizeByPid(id);
        //分页取数据算页数
        int pagesize = size/1000;
        pagesize = pagesize+(size%10000==0?0:1);
        int[] resultData;
        //根据步长算周期内需要计算的时间片段个数
        long diffMinutes = 0l;
        if (livePlan.getStatus()!=3){
            diffMinutes = DateUtil.getMinuteDiff(livePlan.getStartTime(),new Date());
        }else{
            diffMinutes = DateUtil.getMinuteDiff(livePlan.getStartTime(),livePlan.getEndTime());
        }
        int intervalPages = Integer.valueOf(String.valueOf(diffMinutes))/interval;
        intervalPages += Integer.valueOf(String.valueOf(diffMinutes))%interval==0?0:1;
        resultData = new int[intervalPages];
        if (pagesize>0){
            for (int i = 0; i < pagesize; i++) {
                List<LiveOrder> list = liveOrderService.getList(id,i*1000,1000);
                for (LiveOrder data: list) {
                    int subMinute = Integer.valueOf(String.valueOf(DateUtil.getMinuteDiff(livePlan.getStartTime(),data.getCreatedDate())));
                    if (subMinute>=0){
                        int currentSize = 0;
                        if (subMinute/interval==0){
                            currentSize = subMinute/interval;
                        }else{
                            currentSize = subMinute/interval+1;
                        }
                        if (currentSize<=(intervalPages-1)){
                            resultData[currentSize] = resultData[currentSize]+1;
                        }
                    }
                }
            }
        }
        LiveOrderData liveOrderData = new LiveOrderData();
        liveOrderData.setInterval(interval);
        liveOrderData.setStartDate(livePlan.getStartTime());
        liveOrderData.setOrderData(resultData);
        return new ResponseEntity<>(new ResponseResultModel<>(liveOrderData), HttpStatus.OK);
    }


    @RequestMapping("/sendMsgTest")
    public String sendMsgTest() {
        File file = new File("/Users/macbook/Desktop/2018-03-28-20.txt");
        BufferedReader reader = null;
        String temp = null;
        int line = 1;
        try {
            reader = new BufferedReader(new FileReader(file));
            while ((temp = reader.readLine()) != null) {
                temp = temp.substring(19,temp.length());
                JSONObject json = JSONObject.parseObject(temp);
                if (json.getString("classname").equals("XP:ZMsg")){
                    JSONObject content = json.getJSONObject("content");
//                    System.out.println(temp+"=================="+content);
                    JSONObject uinfo = content.getJSONObject("user");
                    User juser = new User(uinfo.getString("id"),uinfo.getString("name"),uinfo.getString("portrait"));
                    try {
                        Long.parseLong(content.getString("count"));
                    }catch (Exception e){
                        System.out.println(json.getString("msgUID")+"===========================");
                    }
                    /*ZanMessage zanMessage = new ZanMessage(content.getIntValue("count"),juser);
                    chatRoomService.mngSendMessage(43,zanMessage);
                    Thread.sleep(100);*/
                }
                line++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return "ok";
    }

    @RequestMapping("/sendMsgTest1")
    public String sendMsgTest1() {
        File file = new File("/Users/macbook/Desktop/2018-03-28-21.txt");
        BufferedReader reader = null;
        String temp = null;
        int line = 1;
        try {
            reader = new BufferedReader(new FileReader(file));
            while ((temp = reader.readLine()) != null) {
                temp = temp.substring(19,temp.length());
                JSONObject json = JSONObject.parseObject(temp);
                if (json.getString("classname").equals("XP:ZMsg")){
                    JSONObject content = json.getJSONObject("content");
//                    System.out.println(temp+"=================="+content);
                    JSONObject uinfo = content.getJSONObject("user");
                    User juser = new User(uinfo.getString("id"),uinfo.getString("name"),uinfo.getString("portrait"));
                    try {
                        Long.parseLong(content.getString("count"));
                    }catch (Exception e){
                        System.out.println(json.getString("msgUID")+"===========================");
                    }

                    /*ZanMessage zanMessage = new ZanMessage(content.getIntValue("count"),juser);
                    chatRoomService.mngSendMessage(43,zanMessage);
                    Thread.sleep(100);*/
                }
                line++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return "ok";
    }
}
